package cn.itsource.user.service.impl;

import cn.itsource.basic.dto.LoginDto;
import cn.itsource.basic.exception.BusinessException;
import cn.itsource.basic.jwt.JwtUtils;
import cn.itsource.basic.jwt.LoginData;
import cn.itsource.basic.jwt.RsaUtils;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.HttpUtil;
import cn.itsource.basic.util.Md5Utils;
import cn.itsource.basic.util.StrUtils;
import cn.itsource.org.mapper.EmployeeMapper;
import cn.itsource.system.domain.Menu;
import cn.itsource.user.constant.WxConstants;
import cn.itsource.user.domain.Logininfo;
import cn.itsource.user.domain.User;
import cn.itsource.user.domain.Wxuser;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.mapper.WxuserMapper;
import cn.itsource.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;


    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private EmployeeMapper employeeMapper;


    //账号登陆
    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //空值校验
        //账号
        String account = loginDto.getAccount();
        //密码
        String checkPass = loginDto.getCheckPass();
        if(StringUtils.isEmpty(account)||StringUtils.isEmpty(checkPass)){
            throw  new BusinessException("信息不能为空");
        }

        //账号校验
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if(logininfo == null){
            throw new BusinessException("账号或密码错误");
        }

        //密码加密加盐 校验
        //前端输入的密码进行加密加盐
        String inputPwd = Md5Utils.encrypByMd5(checkPass + logininfo.getSalt());
        //在和数据库里的密码进行对比
        if(!inputPwd.equals(logininfo.getPassword())){
            throw new BusinessException("账号或密码错误");

        }

        //校验账号是否被禁用
        if(!logininfo.getDisable()){
            throw new BusinessException("账号被禁用，请联系管理员");

        }
        //===================原来使用redis的方式======================
       /* //生成token 并将登录信息(logininfo)保存到redis数据库 设置30M有效
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //封装返回值 Map[token:logininfo]
        //3.使用Map将token和登录对象绑定到AjaxResult的resultObj中响应给前端
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        //因为传给前端后看得到 所以要把密码置空再传
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo",logininfo);*/


        //调用下面提取的方法 利用jwt生成token、登录信息、权限、菜单
        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return map;
    }

    /**
     * 第三方微信登陆
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {
        //1.根据code发送第二个请求：httpUtil，返回json格式字符串
            //准备第二个请求和参数
        String url =WxConstants.GET_ACK_URL.replace("APPID",WxConstants.APPID).replace("SECRET",WxConstants.SECRET)
                .replace("CODE",code);
        //后端通过url来发送请求
        String jsonStr = HttpUtil.httpGet(url);
        //获得以下json格式的数据
        /*
        {
        "access_token":"ACCESS_TOKEN",
        "expires_in":7200,
        "refresh_token":"REFRESH_TOKEN",
        "openid":"OPENID",
        "scope":"SCOPE",
        "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
        }
         */
        //2.使用fastJson进行处理 获取token,openid
        JSONObject jsonObject= JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //3.根据openid去查询 wx_user表
        Wxuser wxuser = wxuserMapper.findByOpenId(openid);
            //如果查到了 说明以前扫过码-->直接免密登录(不需要用户名和密码)
            //如果通过openid查询到了微信用户对象，
            if(wxuser!=null){
                //疑问：user_id可能为Null吗?只要有wxuser 就一定会绑定user_id

                User user = userMapper.findById(wxuser.getUserId());
                //有微信用户 还要判断对应的user是否被删除
                if(user!=null){//并且关联的user也有值==绑定了==免密登录
                    Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());

                    //调用下面提取的方法 利用jwt生成token、登录信息、权限、菜单
                    Map<String, Object> map = loginSuccessJwtHandler(logininfo);

                    return AjaxResult.me().setResultObj(map);
                }
            }

        //如果没有查到 说明是第一次绑定或者关联的user被删除了  传给前端 跳转到绑定页面绑定
        return AjaxResult.me().setSuccess(false).setResultObj("?access_token="+access_token+"&openid="+openid);
    }

    //微信绑定之后免密登录
    @Override
    @Transactional
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone =map.get("phone");
        String verifyCode = map.get("verifyCode");
        String access_token = map.get("access_token");
        String openid = map.get("openid");

        //空值校验
        if(StringUtils.isEmpty(phone)||StringUtils.isEmpty(verifyCode)){
            throw new BusinessException("信息不能为空");
        }

        //判断绑定是否失效--加入直接访问绑定的页面就会都为空 要保证是扫码到绑定页面的
        if(StringUtils.isEmpty(access_token)||StringUtils.isEmpty(openid)){
            throw new BusinessException("绑定失效，请通过扫码绑定！");
        }


        //查询redis中的验证码
        Object redisCode = redisTemplate.opsForValue().get("binder:" + phone);
        //校验微信验证码是否过期
        if (redisCode==null){

            throw  new BusinessException("验证码过期");
        }

        //检验验证码是否输入错误
        if (!verifyCode.equals(redisCode.toString().split(":")[0])){

            throw  new BusinessException("验证码有误，重新输入");

        }

        //"https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID"
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN",access_token).replace("OPENID",openid);


        String JsonStr = HttpUtil.httpGet(url);

        //创建wxuser对象 将JsonStr字符串转换为JsonStr对象
        Wxuser wxuser = json2WxUser(JsonStr);

        //操作数据库
        //通过电话号码查
        User user = userMapper.findByPhone(phone);
        //如果没有通过手机号查到这个user
        if(user==null){
            user = phone2User(phone);
            //创建logininfo对象
            Logininfo logininfo = user2Logininfo(user);
            //先添加logininfo对象
            logininfoMapper.add(logininfo);
            //将登录信息的id设置为user中的登录信息Id
            user.setLogininfoId(logininfo.getId());
            //tianjiauser对象
            userMapper.add(user);
        }
        //如果有 直接将User的id设置为微信用户的Id
        wxuser.setUserId(user.getId());
        wxuserMapper.add(wxuser);

        //免密登录
        Logininfo logininfo = logininfoMapper.findById(user.getLogininfoId());
        //调用下面提取的方法 利用jwt生成token、登录信息、权限、菜单
        Map<String, Object> mapTemp = loginSuccessJwtHandler(logininfo);


        return new AjaxResult().setResultObj(mapTemp);
    }


    //生成jwt的方法
    private Map<String,Object> loginSuccessJwtHandler(Logininfo logininfo){
        //目的，获取四个数据：jwttoken,loginingo,当前登录人的权限,当前登录人的菜单
        //细节：管理员登录，用户登陆(当前登录人的权限和菜单不需要)

        Map<String,Object > map =new HashMap<>();
        LoginData loginData = new LoginData();

        //清空盐值密码
        logininfo.setSalt(null);
        logininfo.setPassword(null);

        map.put("logininfo",logininfo);
        loginData.setLogininfo(logininfo);

        //判断是否是管理员
        if(logininfo.getType()==0){//代表是管理员

            //1.获取当前登录人的权限昨天写过()
            List<String> permissions = employeeMapper.getSns(logininfo.getId());
            map.put("permissions",permissions);
            loginData.setPermissions(permissions);

            //2.获取当前登录人的菜单--难点--四张表加自连接
            List<Menu> menus = employeeMapper.getMenus(logininfo.getId());
            map.put("menus",menus);
            loginData.setMenus(menus);
        }

        try {//3.使用私钥加密【LoginData = logininfo+当前登录人权限+当前登录人菜单】成一个jwttoken
            PrivateKey privateKey = RsaUtils.getPrivateKey(LogininfoServiceImpl.class.
                    getClassLoader().getResource("auth_rsa.pri").
                    getFile());
            String token = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token",token);
        }catch (Exception e){
            e.printStackTrace();
        }
        //4.将以上四个数据添加到Map返回
        return map;
    }

    //将电话转换为User对象
    private  User phone2User(String phone){

        User user = new User();

        user.setUsername(phone);
        user.setPhone(phone);
        //生成盐值
        String salt = StrUtils.getComplexRandomString(32);
        //生成随机密码
        String password = StrUtils.getComplexRandomString(6);
        //加密加盐
        String md5Pwd = Md5Utils.encrypByMd5(password + salt);
        user.setPassword(md5Pwd);
        user.setSalt(salt);
        user.setState(1);

        return user;
    }


    private Logininfo user2Logininfo(User user){
        Logininfo logininfo = new Logininfo();

        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);

        return logininfo;
    }


    private Wxuser json2WxUser(String JsonStr){

        //将json对象利用阿里巴巴的fastjson进行处理-----弄出来
        JSONObject jsonObject = JSONObject.parseObject(JsonStr);

        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        String country = jsonObject.getString("country");
        String province = jsonObject.getString("province");
        String city = jsonObject.getString("city");
        String address=country+province+city;

        wxuser.setAddress(jsonObject.getString(address));

        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }





}




